package it.demosms.service.impl;

import com.alibaba.fastjson.JSON;
import it.demosms.config.RabbitConfig;
import it.demosms.constant.UserConstant;
import it.demosms.service.ifac.SendSmsService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
/**
 * 短信发送
 * @author 季鑫利
 */
public class SendSmsServiceImpl implements SendSmsService {

    /**
     * Redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * rabbit
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * smsKey
     */
    private String smsKey = UserConstant.PHONE;

    /**
     * 短信发送
     * @param phone 手机号
     * @author 季鑫利
     */
    @Override
    public void sendSms(String phone) {
        //随机生成6位的验证码
        Random random = new Random();
        int code = random.nextInt(900000) + 100000;
        //将验证码存入缓存，60s过期
        smsKey = UserConstant.PHONE + phone;
        redisTemplate.opsForValue().set(smsKey, Integer.toString(code), 360, TimeUnit.SECONDS);
        Map map = new HashMap();
        map.put("phone", phone);
        map.put("code", code + "");
        rabbitTemplate.convertAndSend(RabbitConfig.TOPIC_EXCHANGE, "topic.sendSms", JSON.toJSONString(map));
    }
}
